<?php

namespace app\admin\controller\coll;

use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\supplier\Supplier;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Disparity extends Backend
{
    
    /**
     * Pay模型对象
     * @var \app\common\model\coll\Pay
     */
    protected $model = null;
    protected $type = null;
    protected $status = null;

    public function _initialize()
    {
        parent::_initialize();
//        $this->model = new \app\common\model\coll\Pay;
//        $this->view->assign("statusList", $this->model->getStatusList());
        $this->status = array(
            1=>'待审核',
            2=>'已通过',
            3=>'强制终止',
            4=>'驳回',
        );
        $this->type = array(
            1=>'采购',
            2=>'销售',
        );
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        if($this->request->isAjax()){
            $where = [];
            $filter = json_decode($this->request->get('filter'),true);
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'id' && !empty($v)){
                        $where['d.id'] = $v;
                    }
                    if($k == 'type' && !empty($v)){
                        $where['type'] = $v;
                    }
                    if($k == 'source_type' && !empty($v)){
                        $where['source_type'] = $v;
                    }
                    if($k == 'nickname' && !empty($v)){
                        $ids = Db::name('supplier')->where(array('nickname'=>array('like','%'.$v.'%')))->column('id');
                        $where['supplier_id'] = array('in',$ids);
                    }
                    if($k == 'company' && !empty($v)){
                        $ids = Db::name('customer')->where(array('company'=>array('like','%'.$v.'%')))->column('id');
                        $where['customer_id'] = array('in',$ids);
                    }
                    if($k == 'number' && !empty($v)){
                        $where['number'] = array('like','%'.$v.'%');
                    }
                    if($k == 'source_number' && !empty($v)){
                        $where['source_number'] = array('like','%'.$v.'%');
                    }
                }
            }

            $offset = input('offset/d',0);
            $limit = input('limit/d',10);
            $rows = Db::name('disparity')
                ->field('d.*,c.company,s.nickname')
                ->where($where)
                ->alias('d')
                ->join('zax_customer c','d.customer_id = c.id','LEFT')
                ->join('zax_supplier s','d.supplier_id = s.id','LEFT')
                ->limit($offset,$limit)
                ->order('d.id','DESC')
                ->select();
            $total = Db::name('disparity')
                ->where([])
                ->count();

            $types = dill_type();
            foreach ($rows as &$v){
                $v['ytype'] =$types[$v['type']];
                $v['type'] =$this->type[$v['type']];
                $v['source_type'] =$types[$v['source_type']];
                $v['ystatus'] =$v['status'];
                $v['status'] =$this->status[$v['status']];
            }
            return array(
              'rows'=>$rows,
              'total'=>$total,
            );

        }
        return $this->view->fetch();
    }

    public function seach(){
        if($this->request->isAjax()){
            $page = input('offset/d',0);
            $pagesize = input('limit/d',10);

            $filter = trim(input('search'));
            if(!empty($filter)){
                $number = $filter;
                if(stristr($number,'ZF')) {//直发
                    $list = Db::name('factory_sales')->where(array('number'=>array('like','%'.$number.'%'),'status'=>5))->limit($page, $pagesize)->order('id', 'DESC')->select();
                    $total = Db::name('factory_sales')->where(array('number'=>array('like','%'.$number.'%'),'status'=>5))->count();
                    if(empty($list)){return  array(
                            'rows'=>[],
                            'total'=>0,
                        );}

                }else if(stristr($number,'JK')){//采购入库单
                    $list = Db::name('purchase_enter')->where(array('number'=>array('like','%'.$number.'%'),'status'=>2))->limit($page, $pagesize)->order('id', 'DESC')->select();
                    $total = Db::name('purchase_enter')->where(array('number'=>array('like','%'.$number.'%'),'status'=>2))->count();
                    if(empty($list)){return  array(
                            'rows'=>[],
                            'total'=>0,
                        );}
                } else{
                    $list = Db::name('sales_checkout')->where(array('number'=>array('like','%'.$number.'%'),'status'=>4))->limit($page, $pagesize)->order('id', 'DESC')->select();

                    $total = Db::name('sales_checkout')->where(array('number'=>array('like','%'.$number.'%'),'status'=>4))->count();
                    if(empty($list)){return  array(
                            'rows'=>[],
                            'total'=>0,
                        );}
                }
                foreach ($list as &$v){
                    if(stristr($v['number'],'ZF')) {//直发
                        $v['type'] = '直发单';
                    }else if(stristr($v['number'],'JK')){//采购入库单
                        $v['type'] = '采购入库单';
                    } else{
                        $v['type'] = '销售出库单';
                    }
                }
                return array(
                    'rows'=>$list,
                    'total'=>$total,
                );
            }

            $where['status'] = array('<',6);
            $where['status'] = 5;
            $where1 = 'status = 4';
            $where2 = 'status = 2';

            $field = 'id,number,createtime';


            $list = Db::field($field)
                ->table('zax_factory_sales')
                ->union('SELECT ' . $field . ' FROM zax_sales_checkout where '.$where1.'', true)
                ->union('SELECT ' . $field . ' FROM zax_purchase_enter where '.$where2.'', true)
                ->limit($page, $pagesize)
                ->where($where)
                ->order('createtime', 'DESC')
                ->select();

            foreach ($list as &$v){
                if(stristr($v['number'],'ZF')) {//直发
                    $v['type'] = '直发单';
                }else if(stristr($v['number'],'JK')){//采购入库单
                    $v['type'] = '采购入库单';
                } else{
                    $v['type'] = '销售出库单';
                }
            }
            $total1 =  Db::name('factory_sales')->where(array('status'=>array('<',6)))->count();
            $total2 =  Db::name('sales_checkout')->where(array('status'=>array('<',5)))->count();
            $total3 =  Db::name('purchase_enter')->where(array('status'=>array('<',3)))->count();
            return array(
              'rows'=>$list,
              'total'=>$total1+$total2+$total3,
            );
        }
        return $this->view->fetch();
    }
    public function add(){
        if($this->request->isAjax()){
            $type = input('type/d',0);
            $number = input('number');
            if(stristr($number,'ZF')) {//直发
                $row = Db::name('factory_sales')->where(array('number'=>$number))->find();
                if(empty($row)){
                    $this->error('查无单据');
                }
                $source = 12;
            }else if(stristr($number,'JK')){//采购入库单
                $row = Db::name('purchase_enter')->where(array('number'=>$number))->find();
                if(empty($row)){
                    $this->error('查无单据');
                }
                $source = 2;
            } else{
                $row = Db::name('sales_checkout')->where(array('number'=>$number))->find();
                if(empty($row)){
                    $this->error('查无单据');
                }
                $source = 7;
            }
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $num = Db::name('disparity')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $actual_cost = input('actual_cost','');

            if(empty($actual_cost)){
                throw new Exception('金额异常');
            }

            $data = array(
                'source_number'=>$number,
                'source_type'=>$source,
                'source_id'=>$row['id'],
                'number'=>'CJ-T-'.date('Y-m-d').'-'.getnumber($num),
                'supplier_id'=>input('supplier_id/d',0),
                'customer_id'=>input('customer_id/d',0),
                'contacts'=>input('contacts',''),
                'address'=>input('address',''),
                'mobile'=>input('mobile',''),
                'explain'=>input('explain',''),
                'allfare'=>input('allfare/d',0),
                'nowtax'=>input('nowtax/d',0),
                'actual_cost'=>$actual_cost,
                'createtime'=>time(),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'type'=>$type,
                'storehouse_id'=>$row['storehouse_id'],
                'operator'=>session('admin')['nickname'],
            );

            if(empty($data['supplier_id']) && empty($data['customer_id'])){
                $this->error('数据对象不存在');
            }
//            $customer_price = 0;
//            $supplier_price = 0;
            $datas = input('row/a');
//            foreach ($datas as $v){
//                $customer_price += $v['diff_price1']*$v['diff_num'];
//                $supplier_price += $v['diff_price2']*$v['diff_num'];
//            }
//            $data['customer_price'] = $customer_price;
//            $data['supplier_price'] = $supplier_price;

            Db::startTrans();
            try{

                $disparity_id =Db::name('disparity')->insertGetId($data);
                if(empty($disparity_id)){
                    throw new Exception('添加失败');
                }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$disparity_id,
                    'type'=>15,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                foreach ($datas as $v){
                    $gdata[] = array(
                       'goods_id'=>$v['goods_id'],
                       'diff_price1'=>$v['diff_price1'],
                       'tax'=>$v['tax'],
                       'sfhj'=>$v['price_diff'],
//                       'tax1'=>$v['tax1'],
//                       'tax2'=>$v['tax2'],
                       'diff_price2'=>$v['diff_price2'],
                       'diff_num'=>$v['diff_num'],
                       'remark'=>$v['remark'],
                       'disparity_id'=>$disparity_id,
                    );
                }
                $res =  Db::name('disparity_goods')->insertAll($gdata);
                if(!$res){
                    throw new Exception('添加失败');
                }
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        return $this->view->fetch();
    }
    public function getgood(){
        $number = input('number');
        $type = input('type/d',1);
        //判断是什么单据
        if(stristr($number,'ZF')){//直发
            $row = Db::name('factory_sales')->where(array('number'=>$number,'status'=>5))->find();
            if(empty($row)){
                $this->error('查无单据');
            }

            $rows = Db::name('factory_sales_goods')
//                ->field('')
                ->alias('f')
                ->join('goods g','f.goods_id = g.id')
                ->where(array('factory_sales_id'=>$row['id']))
                ->select();
            if($type == 1){//采购
                $srow = Supplier::find($row['supplier_id']);
                unset($row['customer_id']);
                $row['supplier_name'] = $srow['nickname'];
                $row['tax'] = $row['unit_tax'];
                foreach ($rows as $v){
                    $list[] = array(
                        'goods_id'=>$v['goods_id'],
                        'number'=>$v['number'],
                        'title'=>$v['title'],
                        'specs'=>$v['specs'],
                        'goods_num'=>$v['goods_num'],
                        'price'=>$v['unit_price'],
                        'ht_price'=>$v['unit_ht_price'],
                        'sfhj'=>$v['unit_ht_price']*$v['goods_num'],
                    );
                }
            }
            if($type == 2){//销售
                $crow = Customer::find($row['customer_id']);
                unset($row['supplier_id']);
                $row['supplier_name'] = $crow['company'];
                foreach ($rows as $v){
                    $list[] = array(
                        'goods_id'=>$v['goods_id'],
                        'number'=>$v['number'],
                        'title'=>$v['title'],
                        'specs'=>$v['specs'],
                        'goods_num'=>$v['goods_num'],
                        'price'=>$v['sale_price'],
                        'ht_price'=>$v['ht_price'],
                        'sfhj'=>$v['sfhj'],
                    );
                }
            }
        }else if(stristr($number,'JK')){//采购入库单
            $row = Db::name('purchase_enter')->where(array('number'=>$number,'status'=>2))->find();
            if(empty($row)){
                $this->error('查无单据');
            }
            $srow = Supplier::find($row['supplier_id']);
            $row['supplier_name'] = $srow['nickname'];

            $rows = Db::name('purchase_enter_goods')
                ->field('')
                ->alias('f')
                ->join('goods g','f.goods_id = g.id')
                ->where(array('purchase_enter_id'=>$row['id']))
                ->select();
            foreach ($rows as $v){
                $list[] = array(
                    'goods_id'=>$v['goods_id'],
                    'number'=>$v['number'],
                    'title'=>$v['title'],
                    'specs'=>$v['specs'],
                    'goods_num'=>$v['goods_num'],
                    'price'=>$v['unit_price'],
                    'ht_price'=>$v['ht_price'],
                    'sfhj'=>$v['ht_price']*$v['goods_num'],
                );
            }
        }else{
            $row = Db::name('sales_checkout')->where(array('number'=>$number,'status'=>4))->find();
            if(empty($row)){
                $this->error('查无单据');
            }
            $crow = Customer::find($row['customer_id']);
            $row['supplier_name'] = $crow['company'];
            $rows = Db::name('sales_checkout_goods')
//                ->field('')
                ->alias('f')
                ->join('goods g','f.goods_id = g.id')
                ->where(array('sales_checkout_id'=>$row['id']))
                ->select();
            foreach ($rows as $v){
                $list[] = array(
                    'goods_id'=>$v['goods_id'],
                    'number'=>$v['number'],
                    'title'=>$v['title'],
                    'specs'=>$v['specs'],
                    'goods_num'=>$v['goods_num'],
                    'price'=>$v['sale_price'],
                    'ht_price'=>$v['ht_price'],
                    'sfhj'=>$v['sfhj'],
                );
            }
        }
        $crow = Customer::find(isset($row['customer_id'])?$row['customer_id']:0);
        if(empty($row['address'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['contacts'])){
            $row['address'] = $crow['address'];
        }
        if(empty($row['mobile'])){
            $row['mobile'] = $crow['mobile'];
        }
        $row['company'] = $crow['company'];
        return array(
            'code'=>1,
            'list'=>$list,
            'row'=>$row,
        );
    }
    public function edit($ids = null){
        $row = Db::name('disparity')->where(array('id'=>$ids))->find();
        if(empty($row)){
            $this->error('暂无信息');
        }
        if($this->request->isAjax()){

            $actual_cost = input('actual_cost','');
            if(empty($actual_cost)){
                throw new Exception('金额异常');
            }
            $data = array(
                'explain'=>input('explain',''),
                'allfare'=>input('allfare/d',0),
                'nowtax'=>input('nowtax/d',0),
                'actual_cost'=>$actual_cost,
            );
            $rows = input('row/a');

            Db::startTrans();
            try {
                Db::name('disparity')->where(array('id'=>$ids))->update($data);

                foreach ($rows as $v) {
                    Db::name('disparity_goods')->where(array(
                        'disparity_id' => $ids,
                        'goods_id' => $v['goods_id'],
                    ))->update(array(
                        'diff_price1' => $v['diff_price1'],
                        'diff_price2' => $v['diff_price2'],
                        'diff_num' => $v['diff_num'],
                        'remark' => $v['remark'],
                        'tax' => $v['tax'],
                        'sfhj'=>$v['price_diff'],
                    ));
                }
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'修改成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $where = array('disparity_id'=>$ids);
        switch ($row['source_type']){
            case 12://直发单
                $where['factory_sales_id'] = $row['source_id'];
                $srow = Db::name('factory_sales')->find($row['source_id']);
                $join = 'factory_sales_goods';
                break;
            case 7://出库单
                $where['sales_checkout_id'] = $row['source_id'];
                $srow = Db::name('sales_checkout')->find($row['source_id']);
//                $join = "'sales_checkout_goods s','d.goods_id = s.goods_id'";
                $join = 'sales_checkout_goods';
                break;
            case 2://入库单
                $where['purchase_enter_id'] = $row['source_id'];
                $srow = Db::name('purchase_enter')->find($row['source_id']);
                $join = 'purchase_enter_goods';
                break;
        }
//        exit;
        $list = Db::name('disparity_goods')
            ->field('g.title,g.number,g.id,g.specs,d.goods_id,s.goods_num,g.unit,s.*,diff_num,diff_price1,diff_price2,d.remark,d.sfhj as dsfhj,d.tax as dtax')
            ->where($where)
            ->alias('d')
            ->join(''.$join.' s','d.goods_id = s.goods_id')
            ->join('goods g','d.goods_id = g.id')
            ->select();

        foreach ($list as &$v){
            if(!isset($v['sfhj'])){
                $v['sfhj'] = $v['ht_price']*$v['goods_num'];
            }
            if($row['type'] == 1){
                if(isset($v['unit_price'])){
                    $v['price'] = $v['unit_price'];
                }
            }else{
                if(isset($v['sale_price'])){
                    $v['price'] = $v['sale_price'];
                }
            }
        }

        $crow = Customer::find($row['customer_id']);
        $this->assign('company',isset($crow['company'])?$crow['company']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function detail($ids = null){
        $row = Db::name('disparity')->where(array('id'=>$ids))->find();
        if(empty($row)){
            $this->error('暂无信息');
        }
        $where = array('disparity_id'=>$ids);
        switch ($row['source_type']){
            case 12://直发单
                $where['factory_sales_id'] = $row['source_id'];
//                $srow = Db::name('factory_sales')->find($row['source_id']);
                $join = 'factory_sales_goods';
                $con = 'factory/sales';
                $name = '直发单';
                break;
            case 7://出库单
                $where['sales_checkout_id'] = $row['source_id'];
//                $srow = Db::name('sales_checkout')->find($row['source_id']);
//                $join = "'sales_checkout_goods s','d.goods_id = s.goods_id'";
                $join = 'sales_checkout_goods';
                $con = 'sales/checkout';
                $name = '出库单';
                break;
            case 2://入库单
                $where['purchase_enter_id'] = $row['source_id'];
//                $srow = Db::name('purchase_enter')->find($row['source_id']);
                $join = 'purchase_enter_goods';
                $con = 'purchase/enter';
                $name = '入库单';
                break;
        }
        $list = Db::name('disparity_goods')
            ->field('g.title,g.number,g.id,g.specs,d.goods_id,s.goods_num,g.unit,s.*,diff_num,diff_price1,diff_price2,d.remark,d.sfhj as dsfhj,d.tax as dtax')
            ->where($where)
            ->alias('d')
            ->join(''.$join.' s','d.goods_id = s.goods_id')
            ->join('goods g','d.goods_id = g.id')
            ->select();

        foreach ($list as &$v){
            if(!isset($v['sfhj'])){
                $v['sfhj'] = $v['ht_price']*$v['goods_num'];
            }
            if($row['type'] == 1){
                if(isset($v['unit_price'])){
                    $v['price'] = $v['unit_price'];
                }
            }else{
                if(isset($v['sale_price'])){
                    $v['price'] = $v['sale_price'];
                }
            }
            if($v['dtax'] >0){
                $v['dbalance'] = bcdiv($v['dsfhj'],(1+$v['dtax']),4);
            }else{
                $v['dbalance'] = $v['dsfhj'];
            }
        }

        $crow = Customer::find($row['customer_id']);
        $this->assign('company',isset($crow['company'])?$crow['company']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        $this->assign('con',$con);
        $this->assign('name',$name);
        return $this->view->fetch();
    }
    public function finish($ids){
        $state = input('state/d',1);

        $row = Db::name('disparity')->find($ids);
        if(empty($row)){
            $this->error('非法操作');
        }
        if($row['status'] !=1){
            $this->error('状态异常');
        }
        Db::startTrans();
        try{
            if($state == 1){
                Db::name('disparity')->where(array('id'=>$ids))->update(array('status'=>2));
                $data = array(
                    'source'=>15,
                    'cost'=>$row['actual_cost'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'source_id' => $row['id'],
                    'obj_id' => $row['customer_id'],
                    'operator'=>$row['operator'],
                    'controller'=>'coll/disparity',
                    'number'=>$row['number'],
                    'createtime'=>time(),
                    'storehouse_id' => isset($row['storehouse_id'])?$row['storehouse_id']:0,
                    'explain'=>$row['explain'],//摘要
                );

                if($row['customer_id'] >0){//客户差价
                    $is_income = 1;//收入

                    $custrow = Customer::find($row['customer_id']);
                    $data['cost'] = $row['actual_cost'];
                    $data['is_income'] = $is_income;
                    $data['obj_id'] = $row['customer_id'];
                    $data['settle_name'] = $custrow['company'];
                    $data['explain'] = $row['explain'];
                    $res = Db::name('analysis')->insert($data);

                }
                if($row['supplier_id'] >0){//供应商差价
                    $is_income = 2;
                    $srow = Supplier::find($row['supplier_id']);
                    $data['cost'] =$row['actual_cost'];
                    $data['is_income'] = $is_income;
                    $data['obj_id'] = $row['supplier_id'];
                    $data['settle_name'] = $srow['nickname'];
                    $data['explain'] = $row['explain'];

                    $res = Db::name('analysis')->insert($data);
                }
                if(empty($res)){
                    throw new Exception('财务数据创建失败');
                }
            }else{
                Db::name('disparity')->where(array('id'=>$ids))->update(array('status'=>4));
            }
            //添加审核记录
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>$state,
                'createtime'=>time(),
                'controller'=>'coll/disparity',
                'source_id'=>$ids,
                'source'=>15,
                'remark'=>'差价单据',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function cancelbill($ids = null){
        $row = Db::name('disparity')->where(array('id'=>$ids))->find();
        if(!$row){
            $this->error('非法操作');
        }
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if($row['status'] != 2){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>15,
            'source_id' => $row['id'],
        ))->find();

        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        Db::startTrans();
        try {
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            $dgoods = Db::name('disparity_goods')->where(array('disparity_id'=>$ids))->select();
            foreach ($dgoods as $v){
                if($v['is_share'] == 1){//已经平摊的需要可逆
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }

                    $balance = bcsub($hgood['balance'],$v['sfhj'],4);
                    $weighting_cost = bcdiv($balance,$hgood['stock'],4);

                    $GoodsHouseStock = new GoodsHouseStock;
                    $GoodsHouseStock->save(array(
//                            'cumulative'=>$row['goods_num']+$groww['cumulative'],
                        'weighting_cost'=>$weighting_cost,
                        'balance'=>$balance,
                    ),array('id'=>$hgood['id']));
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'差价单据',
                        'type_id'=>$ids,
                        'enter_num'=>0,
                        'out_num'=>0,
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
                        'controller'=>'coll/disparity',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$weighting_cost, //记录的金额应该是入库的加权单价
                        'bill_cost'=>$v['sfhj'], //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                        'is_cancel'=>1,
                        'source'=>15
                    ));
                }
            }


            Db::name('disparity')->where(array('id'=>$ids))->update(array('status'=>3));

            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 15,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'coll/disparity',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'coll/disparity',
                'source_id'=>$ids,
                'source'=>15,
                'remark'=>'差价单据',
                'number'=>isset($row['number'])?$row['number']:'',
            ));

            //财务单据作废
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }


            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    public function share($ids = null){
        $row = Db::name('disparity')->where(array('id'=>$ids))->find();
        if(empty($row)){
            $this->error('暂无信息');
        }
        $where = array('disparity_id'=>$ids);
        switch ($row['source_type']){
            case 12://直发单
                $where['factory_sales_id'] = $row['source_id'];
//                $srow = Db::name('factory_sales')->find($row['source_id']);
                $join = 'factory_sales_goods';
                $con = 'factory/sales';
                $name = '直发单';
                break;
            case 7://出库单
                $where['sales_checkout_id'] = $row['source_id'];
//                $srow = Db::name('sales_checkout')->find($row['source_id']);
//                $join = "'sales_checkout_goods s','d.goods_id = s.goods_id'";
                $join = 'sales_checkout_goods';
                $con = 'sales/checkout';
                $name = '出库单';
                break;
            case 2://入库单
                $where['purchase_enter_id'] = $row['source_id'];
//                $srow = Db::name('purchase_enter')->find($row['source_id']);
                $join = 'purchase_enter_goods';
                $con = 'purchase/enter';
                $name = '入库单';
                break;
        }
        $list = Db::name('disparity_goods')
            ->field('g.title,g.number,g.specs,d.goods_id,s.goods_num,g.unit,s.*,diff_num,diff_price1,diff_price2,d.remark,d.sfhj as dsfhj,d.tax as dtax,d.id,d.is_share')
            ->where($where)
            ->alias('d')
            ->join(''.$join.' s','d.goods_id = s.goods_id')
            ->join('goods g','d.goods_id = g.id')
            ->select();

        foreach ($list as &$v){
            if(!isset($v['sfhj'])){
                $v['sfhj'] = $v['ht_price']*$v['goods_num'];
            }
            if($row['type'] == 1){
                if(isset($v['unit_price'])){
                    $v['price'] = $v['unit_price'];
                }
            }else{
                if(isset($v['sale_price'])){
                    $v['price'] = $v['sale_price'];
                }
            }
            if($v['dtax'] >0){
                $v['dbalance'] = bcdiv($v['dsfhj'],(100+$v['dtax'])/100,4);
            }else{
                $v['dbalance'] = $v['dsfhj'];
            }
            $v['stock'] = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
        }

        $crow = Customer::find($row['customer_id']);
        $this->assign('company',isset($crow['company'])?$crow['company']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        $this->assign('con',$con);
        $this->assign('name',$name);
        return $this->view->fetch();
    }
    public function sharegoods($ids){
        $row = Db::name('disparity')->where(array('id'=>$ids))->find();
        $grow = Db::name('disparity_goods')->where(array('disparity_id'=>$ids,'id'=>input('did/d',0)))->find();
        if($grow['is_share'] !=0){
            $this->error('已分摊');
        }

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        Db::startTrans();
        try {
            $groww = Db::name('goods_house_stock')->where(array('goods_id' => $grow['goods_id'], 'storehouse_id' => $row['storehouse_id']))->find();
            if (empty($groww['stock'])) {
                throw new Exception('库存为0');
            }

            $dbalance = bcdiv($grow['sfhj'],(100+$grow['tax'])/100,4);
            $balance = bcadd($groww['balance'],$dbalance,4);
            $weighting_cost = bcdiv($balance,$groww['stock'],4);

            $GoodsHouseStock = new GoodsHouseStock;
            $GoodsHouseStock->save(array(
//                            'cumulative'=>$row['goods_num']+$groww['cumulative'],
                'weighting_cost'=>$weighting_cost,
                'balance'=>$balance,
            ),array('id'=>$groww['id']));
            //库存变化
            Db::name('goods_stock_log')->insert(array(
                'goods_id' => $grow['goods_id'],
                'createtime' => time(),
                'number' => $row['number'],
                'type' => '差价单据',
                'source'=>15,
                'type_id' => $row['id'],
                'enter_num' => 0,
                'before_num' => $groww['stock'],
                'now_num' => $groww['stock'],
                'storehouse_id' => $row['storehouse_id'],
                'controller' => 'coll/disparity',
                'admin_id' => session('admin')['id'],
                'group_id' => $group['group_id'],
                'company' => $group['name'],
                'operator' => session('admin')['nickname'],
                'final_cost' => $weighting_cost, //记录的金额应该是入库的加权单价
                'bill_cost' => $grow['sfhj'], //记录的金额应该是入库的采购成本
                'balance' => $balance, //记录的金额当前库存总额
            ));
            Db::name('disparity_goods')->where(array('id'=>input('did/d',0)))->update(array('is_share'=>1));
            Db::commit();
            return  array(
                'code'=>1,
                'msg'=>'分摊成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
